package com.example.audiotunning;

import android.os.AsyncTask;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;


interface UdpReceiverListener {
    void onDataReceived(byte[] data, String senderIp, int senderPort);
    void onError(String errorMsg);
}


/**
 * UDP通信工具类，使用线程实现数据接收
 */
public class UdpCommunication {
    private static final int BUFFER_SIZE = 256;
    private DatagramSocket socket;
    private int localPort;
    private String localIp;
    private UdpReceiverListener listener;
    private Thread receiveThread;
    private boolean isReceiving;

    /**
     * 初始化UDP通信类
     * @param localPort 本地监听端口
     */
    /**
     * 初始化UDP通信类
     * @param localIp 本地监听IP地址
     * @param localPort 本地监听端口
     */
    public UdpCommunication(String localIp, int localPort) {
        this.localIp = localIp;
        this.localPort = localPort;
        try {
            InetAddress address = InetAddress.getByName(localIp);
            socket = new DatagramSocket(localPort, address);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置接收数据监听器
     * @param listener 监听器接口实现
     */
    public void setUdpReceiverListener(UdpReceiverListener listener) {
        this.listener = listener;
    }

    /**
     * 开始接收UDP数据包
     */
    public void startReceiving() {
        if (receiveThread == null || !receiveThread.isAlive()) {
            isReceiving = true;
            receiveThread = new Thread(new ReceiverRunnable());
            receiveThread.start();
        }
    }

    /**
     * 停止接收UDP数据包
     */
    public void stopReceiving() {
        isReceiving = false;
        if (receiveThread != null) {
            receiveThread.interrupt();
        }
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }

    /**
     * 发送UDP数据包
     * @param data 要发送的数据
     * @param targetIp 目标IP地址
     * @param targetPort 目标端口
     */
    public void sendData(final byte[] data, final String targetIp, final int targetPort) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InetAddress address = InetAddress.getByName(targetIp);
                    DatagramPacket packet = new DatagramPacket(
                            data, data.length, address, targetPort);
                    socket.send(packet);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onError("未知主机: " + targetIp);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onError("发送数据失败: " + e.getMessage());
                    }
                }
            }
        }).start();
    }

    /**
     * 关闭UDP套接字
     */
    public void close() {
        stopReceiving();
        if (socket != null && !socket.isClosed()) {
            socket.close();
        }
    }

    /**
     * UDP数据接收线程
     */
    private class ReceiverRunnable implements Runnable {
        @Override
        public void run() {
            byte[] receiveBuffer = new byte[BUFFER_SIZE];
            while (isReceiving && !Thread.currentThread().isInterrupted()) {
                try {
                    DatagramPacket receivePacket = new DatagramPacket(
                            receiveBuffer, BUFFER_SIZE);
                    socket.receive(receivePacket);

                    final byte[] data = new byte[receivePacket.getLength()];
                    System.arraycopy(receivePacket.getData(),
                            receivePacket.getOffset(), data, 0, data.length);

                    final String senderIp = receivePacket.getAddress().getHostAddress();
                    final int senderPort = receivePacket.getPort();

                    if (listener != null) {
                        // 如果需要在UI线程处理数据，使用Handler
                        // handler.post(new DataHandler(data, senderIp, senderPort));

                        // 或者使用runOnUiThread（需要Activity上下文）
                        // activity.runOnUiThread(new DataHandler(data, senderIp, senderPort));

                        // 直接回调（在非UI线程，注意不要直接操作UI）
                        listener.onDataReceived(data, senderIp, senderPort);
                    }
                } catch (IOException e) {
                    if (!socket.isClosed() && isReceiving) {
                        e.printStackTrace();
                        if (listener != null) {
                            listener.onError("接收数据失败: " + e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * UDP数据接收监听器接口
     */

}